#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

/**
 * ./testchrdevbase /dev/* -w abc
 * ./testchrdevbase /dev/* -r
 */
int main(int argc, char *argv[])
{
    int fd;
    char buf[1024];
    int len;
    
    /* 1. 判断参数 */
    if (argc < 3)
    {
        printf("Usage: %s /dev/* -w <string>\n", argv[0]);
        printf("       %s /dev/* -r\n", argv[0]);
        return -1;
    }
    
    /* 2. 打开文件 */
    fd = open(argv[1], O_RDWR);
    if (fd == -1)
    {
        printf("can not open file %s\r\n", argv[1]);
        return -1;
    }
    
    /* 3. 写文件或读文件 */
    
    if ((0 == strcmp(argv[2], "-w")) && (argc == 4))
    {
        len = strlen(argv[3]) + 1;
        len = len < 1024 ? len : 1024;
        
        write(fd, argv[3], len);
    }
    else
    {
        len = read(fd, buf, 1024);
        buf[1023] = '\0';
        printf("APP read : %s\r\n", buf);
    }
    
    close(fd);
    
    return 0;
}
